/**
 * Created by zhoulin on 2019/4/3.
 */
//表格初始化配置
var tableInit = function () {

    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        }, {
            field: 'id',
            title: 'ID',
            align: 'center',
            sortable: true
        }, {
            field: 'name',
            title: '角色名',
            align: 'center',
            sortable: true
        }, {
            field: 'description',
            title: '描述',
            align: 'center',
            sortable: true
        }, {
            field: 'status',
            title: '状态',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return '<span class="label label-danger" >禁用</span>';
                } else if (value == 1) {
                    return '<span class="label label-primary" >正常</span>';
                } else {
                    return "其他";
                }

            }
        }, {
            field: 'sort',
            title: '排序',
            align: 'center'
        }, {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            sortable: true,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            searchText: params.searchText,
            sortName: params.sortName,      //排序列名
            sortOrder: params.sortOrder, //排位命令（desc，asc）
            deptId: sessionStorageUtils.getJson(storageKey.sessionStorageKey.deptId) //部门id
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.business_appRole_list, queryParams, columns), {
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'appRole:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '输入角色名');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['appRole:add', 'appRole:update', 'appRole:del', 'appRole:assignPermission'],//本页权限数组
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        //添加
        add: function () {
            var that = this;
            var index = layer.open({
                type: 2,
                title: "新增",
                content: "edit.html?id=",
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //修改
        update: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            list = list[0];
            var index = layer.open({
                type: 2,
                title: "修改",
                content: "edit.html?id=" + list.id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        //删除
        del: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            for (var item in list) {
                ids += list[item].id + ",";
            }
            var confirm = layer.confirm('确定删除选中用户？', {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Put(that, _HOST + _API.business_appRole_delete + ids, {}, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response)
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });

        },
        //分配权限
        assignPermission: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }

            list = list[0];
            //获取当前登录人拥有的权限
            Get(that, _HOST + _API.business_appRole_getPermissionZTreeNodes + "/" + list.id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            console.log(response.list);
                            var html = '<ul id="treeDemo" class="ztree"></ul>';
                            var confirm = layer.confirm(html, {
                                title: "权限",
                                btn: ['分配权限', '取消'], //按钮
                                shadeClose: false,
                                area: ['40%', '100%']
                            }, function () {
                                console.log("确定");
                                //选中角色
                                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                                nodes = zTree.getCheckedNodes(true);
                                if (nodes.length <= 0) {
                                    parent.layer.msg('请至少选中一个权限', {time: 1500, icon: 5});
                                    return;
                                }

                                //得到选中节点ID
                                var rolePermission = [];
                                for (var i = 0; i < nodes.length; i++) {
                                    rolePermission.push({"rid": list.id, "pid": nodes[i].id})
                                }

                                console.log(rolePermission);

                                Put(that, _HOST + _API.business_appRole_assignPermission, rolePermission, true, that.permissions[index])
                                    .then(function (response) {
                                        // 响应成功回调
                                        console.log(response);
                                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                                        if (response) {
                                            if (response.success) {
                                                layer.msg(response.msg, {icon: 1});
                                            } else {
                                                layer.msg(response.msg, {time: 1500, icon: 5});
                                            }
                                        }
                                    })

                            });
                            //树形初始化
                            var setting = {
                                check: {
                                    enable: true,
                                },
                                data: {
                                    simpleData: {
                                        enable: true,
                                        idKey: "id",
                                        pIdKey: "pid",
                                        rootPId: 0
                                    }
                                },
                                callback: {
                                    onClick: function (e, treeId, treeNode, clickFlag) {
                                        $.fn.zTree.getZTreeObj("treeDemo").checkNode(treeNode, !treeNode.checked, true);
                                    }
                                },

                            };
                            $.fn.zTree.init($("#treeDemo"), setting, response.list);

                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })

        }
    },
});

$(function () {
    //初始化表格
    tableInit();
});
